package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a20_N皇后复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/16
 */
public class a20_N皇后复习2 {

    public static void main(String[] args) {
        a20_N皇后复习2 a20_n皇后复习2 = new a20_N皇后复习2();
        System.out.println(a20_n皇后复习2.solveNQueens(4));
    }
    public List<List<String>> solveNQueens(int n) {
        char[][] grid = new char[n][n];
        for (char[] chars : grid) {
            Arrays.fill(chars, '.');
        }

        List<List<String>> resultList = new ArrayList<>();
        traversal(resultList, grid, 0);
        return resultList;

    }

    private void traversal(List<List<String>> resultList,
                           char[][] grid,
                           int row){
        if(row == grid.length){
            List<String> result = new ArrayList<>();
            for (char[] chars : grid) {
                result.add(new String(chars));
            }
            resultList.add(result);
            return;
        }
        for (int col = 0; col < grid[row].length; col++) {
            if(isValid(grid,row,col)){
                grid[row][col] = 'Q';
                traversal(resultList,grid,row+1);
                grid[row][col] = '.';
            }
        }
    }

    private boolean isValid(char[][] grid, int row, int col) {
        //列
        for (int i = 0; i < row; i++) {
            if(grid[i][col] == 'Q'){
                return false;
            }
        }

        //45°
        for (int i = row - 1,j = col - 1; i >= 0 && j >= 0; i--,j--) {
            if(grid[i][j] == 'Q'){
                return false;
            }
        }

        //135°
        for (int i = row - 1,j = col + 1; i >= 0 && j < grid[0].length; i--,j++) {
            if(grid[i][j] == 'Q'){
                return false;
            }
        }
        return true;
    }
}
